//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by 周小伟 on 16/8/24.
//  Copyright © 2016年 周小伟. All rights reserved.
//

import UIKit
import AFNetworking

private let weiboDomain = "com.baidu.data.error"

private let hostname = "https://api.weibo.com/"
/// 测试环境
//private let hostname = "https://test.weibo.com/"
enum HTTPMethod:String{
    case POST = "POST"
    case GET = "GET"
}

class NetworkTools: AFHTTPSessionManager {
    static let sharedTools:NetworkTools = {
        let url = NSURL(string: hostname)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    func requestJsonDict(method:HTTPMethod,urlString:String,parmaters:[String:AnyObject]?,finished:(result:[String:AnyObject]?,error:NSError?)->()){
        if method == HTTPMethod.GET{
            GET(urlString,parameters: parmaters,success: {(_,result)-> Void in
                if let dict = result as? [String:AnyObject]{
                    finished(result: dict, error: nil)
                    return
                }
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                finished(result: nil, error: dataError)
            }){ (_,error)->Void in
                finished(result: nil, error: error)
                print(error)
            }
        }else{
            POST(urlString, parameters: parmaters, success: { (_, result) in
                if let dict = result as? [String:AnyObject]{
                    finished(result: dict, error: nil)
                }
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                finished(result: nil, error: dataError)
                }) { (_, error) in
                    finished(result: nil, error: error)
                    print(error)
            }
        }
    }
    
    func uploadImage(urlString:String,parmaters:[String:AnyObject]?,imageData:NSData,finished:(result:[String:AnyObject]?,error:NSError?) -> ()){
        
        POST(urlString, parameters: parmaters, constructingBodyWithBlock: { (multipartFormData) in
            multipartFormData.appendPartWithFileData(imageData, name: "pic", fileName: "OMG", mimeType: "image/jpeg")
            }, success: { (_, result) in
                if let dict = result as? [String:AnyObject]{
                    finished(result: dict, error: nil)
                }
            }) { (_, error) in
                finished(result: nil, error: error)
                print(error)
        }
        
    }
}
